package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.socket.MessageType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.socket.bean.BaseDataPiece;
import com.ruoyi.common.core.domain.entity.socket.bean.BoatMessage;
import com.ruoyi.common.core.domain.entity.socket.bean.FenceInfo;
import com.ruoyi.common.core.domain.entity.system.SysBoat;
import com.ruoyi.common.core.domain.entity.system.SysFence;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.handler.socket.SocketMessageHandler;
import com.ruoyi.manager.SocketChannelManager;
import com.ruoyi.system.service.ISysBoatService;
import com.ruoyi.system.service.ISysFenceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 电子围栏Controller
 *
 * @author ruoyi
 * @date 2023-05-22
 */
@Slf4j
@RestController
@RequestMapping("/system/fence")
public class SysFenceController extends BaseController {
    @Autowired
    private ISysFenceService fenceService;

    @Autowired
    private ISysBoatService sysBoatService;

    /**
     * 查询电子围栏列表(分页)
     */
//    @PreAuthorize("@ss.hasPermi('system:fence:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(SysFence sysFence) {
//        startPage();
//        List<SysFence> list = fenceService.selectfenceList(sysFence);
//        return getDataTable(list);
//    }

    /**
     * 查询电子围栏列表(不分页，一次性查询所有)
     */
    @PreAuthorize("@ss.hasPermi('system:fence:list')")
    @GetMapping("/list")
    public AjaxResult list(SysFence sysFence) {
        List<SysFence> list = fenceService.selectfenceList(sysFence);
        return success(list);
    }

    /**
     * 导出电子围栏列表
     */
    @PreAuthorize("@ss.hasPermi('system:fence:export')")
    @Log(title = "电子围栏", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysFence sysFence) {
        List<SysFence> list = fenceService.selectfenceList(sysFence);
        ExcelUtil<SysFence> util = new ExcelUtil<>(SysFence.class);
        util.exportExcel(response, list, "电子围栏数据");
    }

    /**
     * 获取电子围栏详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:fence:query')")
    @GetMapping(value = "/{fenceId}")
    public AjaxResult getInfo(@PathVariable("fenceId") Long fenceId) {
        return success(fenceService.selectFenceById(fenceId));
    }

    /**
     * 新增电子围栏
     */
    @PreAuthorize("@ss.hasPermi('system:fence:add')")
    @Log(title = "电子围栏", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysFence sysFence) {
        sysFence.setCreateBy(getUsername());
        sysFence.setCreateTime(new Date());
        String[] coordinateArr = sysFence.getCoordinates().split(",");
        sysFence.setCoordinateNum((short) (coordinateArr.length / 2));
        if (Objects.isNull(sysFence.getGreenDistance())) {
            sysFence.setGreenDistance(0);
        }
        if (Objects.isNull(sysFence.getYellowDistance())) {
            sysFence.setYellowDistance(0);
        }

        int rows = fenceService.insertFence(sysFence);
        return toAjax(rows);
    }

    /**
     * 修改电子围栏
     */
    @PreAuthorize("@ss.hasPermi('system:fence:edit')")
    @Log(title = "电子围栏", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysFence sysFence) {
        sysFence.setUpdateBy(getUsername());
        String[] coordinateArr = sysFence.getCoordinates().split(",");
        sysFence.setCoordinateNum((short) (coordinateArr.length / 2));
        sysFence.setUpdateTime(new Date());
        int rows = fenceService.updateFence(sysFence);

        if (rows > 0) { //电子围栏更新成功
            SocketMessageHandler.sendFenceInfoToAllOnlineBoatOfAssignedScenic(sysFence);
        }
        return toAjax(rows);
    }


    /**
     * 删除电子围栏
     */
    @PreAuthorize("@ss.hasPermi('system:fence:remove')")
    @Log(title = "电子围栏", businessType = BusinessType.DELETE)
    @DeleteMapping("/{scenicId}/{fenceIds}")
    public AjaxResult remove(@PathVariable("scenicId") Long scenicId, @PathVariable("fenceIds") Long[] fenceIds) {
        int num = fenceService.deleteFenceByFenceIds(fenceIds);
        if (num > 0) {
            //取第一个被删除的电子围栏id，一般一次只会删除一个电子围栏
            Long firstFenceId = fenceIds[0];
            //去船只表中找出对应景区id和电子围栏id的所有船只列表
            SysBoat sysBoat = new SysBoat();
            sysBoat.setScenicId(scenicId);
            sysBoat.setFenceId(firstFenceId);
            List<SysBoat> boatList = sysBoatService.selectSysBoatList(sysBoat);

            BoatMessage boatMessage = new BoatMessage(MessageType.CONFIG_MESSAGE, (byte) 1);
            FenceInfo fenceInfo = new FenceInfo();
            fenceInfo.setCreateOrUpdateTime(new Date());

            fenceInfo.setGreenDistance(0);
            fenceInfo.setYellowDistance(0);
            fenceInfo.setCoordinateNum((short) 0);

            List<BaseDataPiece> dataPieceList = boatMessage.getDataPieceList();
            dataPieceList.add(fenceInfo);

            SocketChannelManager.sendMsgToAllOnlineBoatOfAssignedScenic(scenicId, boatMessage);

            //向所有对应船只发送当前码头被删除的报文
            boatList.forEach(boat -> {
                SocketChannelManager.sendMsgToAssignedBoat(boat.getBoatId(), boatMessage);
                //同时将所有船只的电子围栏id更新为0,即没有指定电子围栏
                boat.setFenceId(0L);
                sysBoatService.updateSysBoat(boat);
            });
        }
        return toAjax(num);
    }
}
